
package com.kylin.common.core.beans;

import com.alibaba.fastjson2.annotation.JSONField;
import com.kylin.common.core.annotation.JSONSerialized;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 接口通用返回对象
 *
 * @author wuhao
 * @version 1.0 - 2019-02-11
 */
@Data
@ApiModel(description="返回对象", value = "返回对象")
public class ResultBean<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 接口返回码, 0表示成功, 其他看对应的定义
     */
    @JSONField(ordinal = 1)
    @ApiModelProperty(value = "返回码", example="0")
    private int code = GlobalResultCode.SUCCESS.getCode();

    /**
     * 返回的信息(主要出错的时候使用)
     */
    @JSONField(ordinal = 2)
    @ApiModelProperty(value = "返回信息")
    private String msg = GlobalResultCode.SUCCESS.getMsg();

    /**
     * 返回的数据
     */
    @JSONField(ordinal = 3)
    @ApiModelProperty(value = "返回数据对象")
    private T data;

    /**
     * 序列化对象
     */
    @JSONField( serialize = false)
    @ApiModelProperty(hidden = true)
    private transient JSONSerialized[] jsonSerialized;

    @JSONField(serialize = false)
    @ApiModelProperty(hidden = true)
    private transient HashMap<String, Object> resultMap = new HashMap<>();


    public ResultBean() {
        super();
    }

    public ResultBean(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

    public ResultBean(int code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResultBean(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }

    /**
     * 成功
     */
    public static <T> ResultBean<T> onSuccess(){
        return onSuccess(null);
    }

    /**
     * 成功
     * @param data 业务对象
     */
    public static <T> ResultBean<T> onSuccess(T data){
        ResultBean<T> result = new ResultBean<>(GlobalResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    /**
     * 输出键值对象
     */
    public ResultBean<T> put(String key, Object value) {
        this.getResultMap().put(key, value);
        this.setData((T) this.resultMap);
        return this;
    }

    /**
     * 操作失败
     * @param msg 错误消息
     */
    public static <T> ResultBean<T> onFail(String msg){
        return new ResultBean<>(GlobalResultCode.FAIL.getCode(), msg);
    }

    /**
     * 异常错误
     * @param resultCode 异常错误
     */
    public static <T> ResultBean<T> onError(ResultCode resultCode){
        return new ResultBean<>(resultCode.getCode(), resultCode.getMsg());
    }
}
